import React, {useCallback, useEffect, useRef, useState} from 'react';
import {Image, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {useNavigation, useRoute} from '@react-navigation/native';
import screen from '../../utils/screen';
import RNLocation from 'react-native-location';
import {useAppStore} from '../../store/useAppStore';
import store from 'react-native-simple-store';
import {WatchComponent} from './component/watch';
import {locToDegrees, transitPredict} from '../../utils/satUtil';
import NativeUtil, {isIos} from '../../utils/native';
import RNFetchBlob from 'rn-fetch-blob';
import Container from '../../components/Container';
import Images from '../../images/images';
import {useLoading} from '../../components/loading/useLoading';
import {useModal} from '../../components/useModal';
import TouchableView from '../../components/touchableView';
import {useToast} from '../../components/toast/useToast';
import SatMenu from './component/satMenu';
import CompassHeading from '../../utils/compassHeading';
import SatToast from './component/satToast';
import BleUtil from '../../utils/bleUtil';
import {addTleInfoCmd} from '../../utils/bleCmd';
import SatListItem from '../../components/satListItem';
// const mySatIdList = ['47299','51836','54687','45019','46810','48426','55133','48864','49027','45602','45603']
const bgWidth = screen.width - screen.PIXEL_90
const defaultTleData = ["TIANQI-5\n1 45019U 20003D   23067.14792208  .00028423  00000+0  76930-3 0  9991\n2 45019  97.1833 126.0600 0011493 144.4587 238.9843 15.37583369175514","XINGYUN-2 01\n1 45602U 20028A   23067.20479906  .00004600  00000+0  34890-3 0  9990\n2 45602  97.4522  79.7253 0012184 346.7666 104.0235 15.02646339154548","XINGYUN-2 02\n1 45603U 20028B   23067.11111114  .00004232  00000+0  32252-3 0  9996\n2 45603  97.5373  84.9640 0013034  49.8953 310.3422 15.02511573154537","TIANQI-6\n1 46810U 20076D   23067.20396343  .00005256  00000+0  49582-3 0  9990\n2 46810  35.0047 112.2391 0013565 177.8390 182.2476 14.93138222128875","TIANQI-8\n1 47299U 20102D   23067.22760267  .00033215  00000+0  11509-2 0  9997\n2 47299  97.4286 168.6518 0005002 202.6065 241.2140 15.29755021122626","TIANQI-12\n1 48426U 21039D   23067.12230599  .00006835  00000+0  63849-3 0  9992\n2 48426  35.0074  55.4762 0006376 265.9718  94.0318 14.93523883100141","TIANQI-14\n1 48864U 21055E   23067.00224226  .00006698  00000+0  62791-3 0  9995\n2 48864  35.0062 177.6125 0007359 284.0755  75.9178 14.93382184 93509","TIANQI-15\n1 49027U 21065B   23067.05066099  .00007630  00000+0  71489-3 0  9996\n2 49027  35.0073 299.2551 0008404  16.4480 343.6531 14.93375651 89224","2022-019N\n1 51836U 22019N   23067.15823780  .00025161  00000+0  12884-2 0  9998\n2 51836  97.4848 142.5987 0014255  68.7971  14.6950 15.16499503 56522","2022-167F\n1 54687U 22167F   23067.17114145  .00020881  00000+0  12682-2 0  9999\n2 54687  97.5411 205.7146 0014383 332.3735 200.9636 15.10430194 13401","2023-003A\n1 55133U 23003A   23066.46809373 -.00000064  00000+0  00000+0 0  9991\n2 55133  97.2561 154.3403 0006511  54.6877  39.8781 15.18342988  8686"]
const SatList = ()=>{

    const navigation = useNavigation()
    const route = useRoute()
    const {appState: {location,pressure,currentDevice,debugMode},updateAppState} = useAppStore()
    const loading = useLoading()
    const modal = useModal()
    const toast = useToast()

    const [userHeading, setUserHeading] = useState(0);
    const tleData= useRef(defaultTleData)
    const [satList, setSatList] = useState([]);
    const [time,setTime] = useState(null)
    const timerRef = useRef(null)

    const satToastRef = useRef(null)


    useEffect(()=>{
        store.get('tleData').then(data=>{
            if(data){
                console.log('local tle data:',data)
                tleData.current = data
                updateTleData()
            }else{
                // fetchSatData()
            }

        })

        RNLocation.configure({
            distanceFilter:5.0,
            allowsBackgroundLocationUpdates:false
        })

        // setNav()

        if(isIos()){

            RNLocation.subscribeToHeadingUpdates(heading => {
                // console.log('heading',heading);
                setUserHeading(heading.heading)
            })
        }else{
            RNLocation.getCurrentPermission().then(res=>{
                console.log(res);
            })

        }


        return () => {
            timerRef.current  && clearInterval(timerRef.current)

        };
    },[])


    const updateTleData = ()=>{
        if(currentDevice){
            let cmdList = []
            tleData.current.forEach(it=>{
                const contentArr = it.split('\n')
                let tle1 = contentArr[1]
                let tle2 = contentArr[2]
                let tleId = contentArr[2].substring(2,8)
                let cmd = addTleInfoCmd(tleId,tle1,tle2)
                cmdList.push(cmd)
            })

            console.log(cmdList[0]);
            BleUtil.write(currentDevice.id,cmdList[0])
        }
    }

    const setNav = useCallback(()=>{
        navigation.setOptions({
            headerRight:()=>(
                <TouchableOpacity
                    style={{paddingRight:screen.PIXEL_20}}
                    onPress={()=>{
                        console.log('refresh:',location)
                        // getSatData()
                        modal.showContent(
                            <SatMenu
                                data={satList}
                                onClose={()=>{
                                    modal.close()
                                }}

                            />
                        )
                    }}
                >
                    <Image source={Images.mine_tab_sel} style={{width:screen.PIXEL_30,height:screen.PIXEL_30}}/>
                </TouchableOpacity>
            ),
        })
    },[satList])


    useEffect(()=>{
        console.log('location effect',location);
        if(location){
            getSatData()
            // timerRef.current && clearInterval(timerRef.current)
            // timerRef.current = setInterval(getSatData,2 * 1000)
        }
        // setNav()
    },[location])


    const getSatData = useCallback (()=>{
        if(!location) return
        // loading.show()
        let list = []

        for (let index = 0; index < tleData.current.length; index++) {
            let tle = tleData.current[index]
            let res = transitPredict(tle,location)
            if(res){
                list.push({...res,tle})
            }

        }
        // console.log('satlist:',list);
        setSatList(prev=>{
            if(prev.length > 0){
                list.forEach(item=>{
                    const oldSat = prev.find(it=>{
                        return it.id === item.id
                    })
                    if(oldSat){
                        //是否顺时针运动
                        item.clockwise = item.azimuth > oldSat.azimuth
                        && Math.abs(item.azimuth - oldSat.azimuth) < 180 ? true : false

                    }
                })

            }
            return list
        })
        // setTime(formatTimestamp(new Date(),'yyyy/MM/dd hh:mm:ss'))
        // loading.hide()
    },[loading,satList,time,location])

    //更新卫星数据
    function fetchSatData(){
        loading.show()
        RNFetchBlob.fetch('GET','https://celestrak.org/NORAD/elements/active.txt').then(res=>{
            const mySatIdList = ['47299','51836','54687','45019','46810','48426','55133','48864','49027','45602','45603']
            let subArr = []
            let list = []
            const contentArr = res.data.split('\n')
            for (let i = 0; i < contentArr.length; i++) {
                if(list.length===mySatIdList.length)  break

                if(i % 3 === 0 && i > 0){
                    let tleId = subArr[2].substring(2,8)
                    const findIndex = mySatIdList.findIndex(it=>{
                        return tleId.trim() === it.trim()
                    })
                    if(findIndex> -1){
                        console.log('subArr',subArr);
                        list.push(subArr.join('\n'))
                    }
                    subArr = []
                }
                const str = contentArr[i].trim()
                subArr.push(str)
            }
            console.log('list:',list);
            store.save('tleData',list)
            tleData.current = list
            loading.hide()
        }).catch(e=>{
            console.log('fetch error',e)
        })
    }


    const getHeadingText = useCallback( (angle)=>{
        let prefix
        if(angle >= 1 && angle<=80) prefix = '东北'
        else if(angle>80 && angle <= 100) prefix = '东'
        else if(angle>100 && angle <= 170) prefix = '东南'
        else if(angle>170 && angle <= 190) prefix = '南'
        else if(angle>190 && angle <= 260) prefix = '西南'
        else if(angle>260 && angle <= 280) prefix = '西'
        else if(angle>280 && angle < 360) prefix = '西北'
        else prefix = '北'

        return prefix + parseInt(angle)
    },[])

    return location ?  (
        <Container >
          {/*
            <View style={{width:'100%'}}>
                <Text style={{color:'#333',fontWeight:'700',fontSize:26,textAlign:'center',marginTop:10}}>{getHeadingText(userHeading)}</Text>
                <View style={styles.locWrap}>
                    <View style={{flexDirection:'row'}}>
                        <Text style={styles.locText}>纬度
                            <Text style={styles.locValueText}>  {locToDegrees(location.latitude) }</Text>
                        </Text>
                        <Text style={styles.locText}>经度
                            <Text style={styles.locValueText}>  {locToDegrees(location.longitude) }</Text>
                        </Text>
                    </View>

                    <View style={{flexDirection:'row',marginTop:15}}>
                        <Text style={styles.locText}>气压<Text style={styles.locValueText}>  {pressure}kPa</Text> </Text>
                        <Text style={styles.locText}>海拔<Text style={styles.locValueText}>  { parseInt(location.altitude) }m</Text></Text>
                    </View>
                </View>

            </View>

*/}
            <View style={styles.container}>
                {
                    isIos() ? (
                        <WatchComponent
                            style={{zIndex:-10}}
                            width={bgWidth}
                            heading={userHeading}
                            satList={satList}
                            onItemClick={item=>{
                                if(!item.subItems) return
                                const strList = item.subItems.map(it=>{
                                    return `${it.name}:${it.startTimeZh}后过境，${getHeadingText(it.azimuth)}方向飞行`
                                })
                                strList.push(`${item.name}:${item.startTimeZh}后过境，${getHeadingText(item.azimuth)}方向飞行`)
                                satToastRef.current.showToast(strList)
                            }}
                        />
                    ): (
                        <ScrollView
                            contentContainerStyle={{paddingHorizontal:screen.PIXEL_30}}
                        >
                            {
                                satList.map((item,index)=>{
                                    return (
                                        <SatListItem data={item} key={index}/>
                                    )
                                })
                            }
                        </ScrollView>
                    )
                }

            </View>


            <SatToast ref={satToastRef}/>

            {/*<Text style={{fontSize:12,color:'#53687A',marginBottom:screen.PIXEL_60,alignSelf:'center'}}>卫星数据更新时间:{time}</Text>*/}

        </Container>
    ) : (
        <Container style={styles.container}>
            <Image source={Images.loc_pic} resizeMode={'contain'} style={styles.locImg}/>
            <Text style={styles.locTipText}>请先开启手机定位功能</Text>
        </Container>
    )
}
export default SatList
const styles = StyleSheet.create({
    container:{
        flex: 1
    },
    locWrap:{
        backgroundColor:'#fff',padding:10,marginHorizontal:20,marginTop:20,borderRadius:10
    },
    locText:{
        flex:1,fontSize: 14,color:'#6B8398'
    },
    locValueText:{
        color:'#425668',fontWeight:'500',fontSize:screen.PIXEL_28
    },
    locImg:{
        width:screen.PIXEL_240,height:screen.PIXEL_240
    },
    locTipText:{
        color:'#89A3BB',fontSize:14,marginTop:screen.PIXEL_50
    },
    listMenu:{
        position:'absolute',top:40,right:50,width:200,height:200,backgroundColor:'rgba(0,0,0,0.55)'
    }
})
